/**
 * Created by ZHOUSH on 12/23/2015.
 */
var git_path = 'C:\\GitRoot\\olp_hor_llp\\podium\\LLP\\OracleReport';
var des_path = '\\rdf';
var Promise = require('promise');
var fsex = require('fs.extra');
var pcopy_r = Promise.denodeify(fsex.copyRecursive);
var sync = pcopy_r(git_path, __dirname + des_path);

var exec = require('child_process').execFile;
var pexec = Promise.denodeify(exec);
var rcpath = 'C:\\OracleBuilder\\BIN\\rwconverter.exe';
var dbconn = 'hllp_rpt_supp/temp@OLRSPRD';
var xml_path = '\\rdfxml';
var convert = function (filename) {
    console.log('CONVERT ' + filename + ' START');
    var cmd = [
        dbconn,
        'stype=rdffile',
        'source="' + __dirname + des_path + '\\' + filename + '.rdf"',
        'dtype=xmlfile',
        'dest="' + __dirname + xml_path + '\\' + filename + '.xml"',
        'batch=yes',
        'OVERWRITE=yes'
    ];
    return pexec(rcpath, cmd, {
        env: {
            'ORACLE_HOME': 'c:\\OracleBuilder'
        }
    }).then(function () {
        console.log('CONVERT ' + filename  + ' END');
    }, function (err) {
        console.log('CONVERT ' + filename  + ' ERROR: ' + err);
    });
};

var preaddir = Promise.denodeify(require('fs').readdir);
var pexists = function (path) {
    return new Promise(function (resolve, reject) {
        require('fs').exists(path, function (there) {
            resolve(there);
        });
    });
};
var th = 5;
var convert_all = function (filter) {
    console.log('CONVERT ALL STARTED');
    console.log(__dirname);
    return preaddir(__dirname + des_path).then(function (files) {
        var idx = 0;
        var next = function (file) {
            var filename = (/^(.+)\.rdf$/ig).exec(file);
            if (filename && filename[1] && filter(filename[1]) && idx < th) {
                idx++;
                return convert(filename[1]);
            }
        };
        return files.reduce(function (pre, file) {
            if (pre != null) {
                return pre.then(function () {
                    return next(file);
                })
            }
            return next(file);
        }, null).then(function () {
            console.log('CONVERT ALL END');
        });
    });
};

var insert = function (file) {
    var there = true;
    try {
        require('fs').statSync(__dirname + xml_path + '\\' + file + '.xml');
    } catch (ex) {
        there = false;
    }
    return !there;
};

convert_all(insert).then(console.log, console.log);

exports.sync = sync;
exports.convert = convert;
exports.convert_all = convert_all;
exports.insert_mode = insert;
